package com.norma.netty.study.netty.ws;

import cn.hutool.core.util.ZipUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufInputStream;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.StandardCharsets;
import java.util.zip.Inflater;

/**
 * @author zhangchaofeng
 * @date 2021/5/18
 * @description
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<WebSocketFrame> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
        //文本信息
        if (frame instanceof TextWebSocketFrame) {
            TextWebSocketFrame textFrame = (TextWebSocketFrame) frame;
            log.info("客户端接收的消息是:" + textFrame.text());
        }
        //二进制信息
        if (frame instanceof BinaryWebSocketFrame) {
            String text = decode(frame);
            log.info("BinaryWebSocketFrame = {}", text);
        }
        //ping信息
        if (frame instanceof PongWebSocketFrame) {
            log.info("WebSocket Client received pong");
        }
        //关闭消息
        if (frame instanceof CloseWebSocketFrame) {
            log.info("receive close frame");
            ctx.channel().close();
        }
    }


    private static String unCompress(ByteBuf buf) {
        try {
            byte[] temp = new byte[buf.readableBytes()];
            ByteBufInputStream bis = new ByteBufInputStream(buf);
            bis.read(temp);
            bis.close();
            Inflater deCompressor = new Inflater(true);
            deCompressor.setInput(temp, 0, temp.length);
            StringBuilder sb = new StringBuilder();
            byte[] result = new byte[1024];
            while (!deCompressor.finished()) {
                int resultLength = deCompressor.inflate(result);
                sb.append(new String(result, 0, resultLength, "UTF-8"));
            }
            deCompressor.end();
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    private static String decode(Object msg) {
        BinaryWebSocketFrame frameBinary = (BinaryWebSocketFrame) msg;
        byte[] bytes = new byte[frameBinary.content().readableBytes()];
        frameBinary.content().readBytes(bytes);
        return new String(ZipUtil.unGzip(bytes), StandardCharsets.UTF_8);
    }

}
